package br.com.future.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.apache.log4j.Logger;

import br.com.future.dao.interfaces.TarefaDAOI;
import br.com.future.jdbc.ConnectionFactory;
import br.com.future.log4j.Log4j;
import br.com.future.model.Tarefa;

public class TarefaDAO implements TarefaDAOI {
	
	//chamando o metodo da classe Log4j.
	static Logger logger = Logger.getLogger(Log4j.class);
	
	private Connection conn = null;
	private boolean flag = true;

	public TarefaDAO(Connection conn){
		this.conn  = conn;
	}
	
	public TarefaDAO(){
	}
	
	public Tarefa consultar(int codigoTarefa){
		
		verificarInstanciaDeConnection();
		
		PreparedStatement ps = null;
		ResultSet rs = null;
		Tarefa tarefa = new Tarefa();
		String sql = "SELECT CD_TAREFA, DS_TAREFA FROM AM_TAREFA WHERE CD_TAREFA = ?";
		
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, codigoTarefa);
			rs = ps.executeQuery();
			
			if(rs.next()){
				tarefa.setCodigoTarefa(rs.getInt("CD_TAREFA"));
				tarefa.setDescricaoTarefa(rs.getString("DS_TAREFA"));
			}
			
		}catch (Exception e) {
			//chamando a mensagem.
			logger.error(e.getMessage());
			
		}finally{
			if(flag){
				ConnectionFactory.closeConnectionOracle(conn, rs, ps);
			}
		}
		
		return tarefa;
		
	}
	
	private void verificarInstanciaDeConnection() {
		flag = true;
		
		if(conn == null){
			conn = ConnectionFactory.getConnection();
		}else{
			flag = false;
		}
	}
}